package cn.wolfcode.trip.app.Filter;

import cn.wolfcode.trip.base.util.UploadUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

public class QRCodeFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String uri = req.getRequestURI();
        uri=uri.replace("/QRCode/","");

        int width = 430; // 二维码图片宽度 300
        int height = 430; // 二维码图片高度300

        String format = "gif";// 二维码的图片格式 gif

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        // 指定纠错等级,纠错级别（L 7%、M 15%、Q 25%、H 30%）
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
        // hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度，非负数
        BitMatrix bitMatrix = null;//生成条形码时的一些配置,此项可选
        try {
            bitMatrix = new MultiFormatWriter().encode(uri,
                    BarcodeFormat.QR_CODE,
                    width, //条形码的宽度
                    height, //条形码的高度
                    hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        // 生成二维码
        File outputFile = new File("D:" + File.separator + "mycode.gif");//指定输出路径
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
        response.getOutputStream().write(FileUtils.readFileToByteArray(outputFile));


    }

    @Override
    public void destroy() {

    }
}
